package com.sunspring.zdcall.support;

import com.sunspring.zdcall.dto.QueueDto;
import com.sunspring.zdcall.bo.SourceMaxTime;
import com.sunspring.zdcall.entity.ZdQueueInfo;
import com.sunspring.zdcall.service.QueueService;
import com.sunspring.zdcall.support.cache.FlagTimeCache;
import com.sunspring.zdcall.support.cache.QueueCache;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author WuLei
 * @Date 2018/12/1  14:34
 */
@Order(value = 1)
@Component
@Slf4j
public class MyApplicationRunner implements ApplicationRunner {

    @Autowired
    private QueueCache queueCache;

    @Autowired
    private QueueService queueService;

    @Autowired
    private FlagTimeCache flagTimeCache;



    /**
     * 服务器启动，将当天的队列传入缓存
     * @param applicationArguments
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //将数据库队列放入缓存队列
        List<ZdQueueInfo> todayQueueInfo = queueService.findTodayQueue();
        if (!CollectionUtils.isEmpty(todayQueueInfo)) {
            Map<String, List<ZdQueueInfo>> checkRoomMap = todayQueueInfo.stream().collect(Collectors.groupingBy(ZdQueueInfo::getCheckId));

            checkRoomMap.forEach((s, queueInfoList) -> {
                if (!CollectionUtils.isEmpty(queueInfoList)) {
                    //todo 缓存最大队列号
                    String maxQueueId = queueService.findMaxQueueId(s,queueInfoList.get(queueInfoList.size() - 1).getCheckInTime());
                    String m2 = StringUtils.substring(maxQueueId,maxQueueId.length() - 3,maxQueueId.length());
                    queueCache.setQueueId(s, m2);
                    for (ZdQueueInfo qi : queueInfoList) {
                        QueueDto queueDto = new QueueDto();
                        BeanUtils.copyProperties(qi, queueDto);
                        if (qi.getCheckStatus() == 0) {
                            queueCache.add(queueDto);
                        } else {
                            queueCache.add(queueDto, false);
                        }
                    }
                }
            });
        }
        //缓存flagTime
        checkFlagTime();
    }

    private void checkFlagTime() {
        List<SourceMaxTime> list = queueService.findMaxCheckInTime();
        if (!list.isEmpty()) {
            list.forEach(sourceMaxTime -> {
                flagTimeCache.set(sourceMaxTime.getSource(),sourceMaxTime.getTime());
            });
        }
    }


}
